import { ref, onMounted, onUnmounted, computed } from "vue";
import {filter} from '../util/todoStorage';

const validHash = ["all", "active", "completed"];
/**
 *  获取过滤后的数据
 *  @param {Array} todosRef 数据源
 */
export default function useFilter(todosRef) {
	const visibilityRef = ref("all");

	/**
	 * 路由hash 处理函数
	 */
	const onHashChange = () => {
		const hash = location.hash.replace(/#\/?/, "");
		if (validHash.includes(hash)) {
			visibilityRef.value = hash;
		} else {
			localStorage.hash = "";
			visibilityRef.value = "all";
		}
	};

	// 监听路由的hash变化
	onMounted(() => {
        onHashChange();
		window.addEventListener("hashchange", onHashChange);
	});

	// 当组件销毁时，取消监听路由的hash变化
	onUnmounted(() => {
		window.removeEventListener("hashchange", onHashChange);
	});

    const filteredTodosRef = computed(()=>{
       return filter(todosRef.value,visibilityRef.value)
    })

    const remainingRef = computed(()=>{
        return filter(todosRef.value,'active').length
    })

    const completedRef = computed(()=>{
        return filter(todosRef.value, "completed").length;
    })

	return {
		visibilityRef,
		filteredTodosRef,
		remainingRef,
		completedRef
	};
}
